package com.pur.zsms.matermanage.mater.web;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.pur.zsms.accountmanage.vo.AccountVo;
import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.filter.AttributeListenerUtil;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.common.util.ApplicationUtil;
import com.pur.zsms.matermanage.mater.service.IMaterService;
import com.pur.zsms.matermanage.mater.vo.MaterValueVo;
import com.pur.zsms.matermanage.mater.vo.MaterVo;
import com.pur.zsms.matermanage.mater.vo.MaterVoForSup;
import com.pur.zsms.matermanage.mater.vo.ShoppingCartMaterSupplierVo;
import com.pur.zsms.matermanage.mater.vo.ShoppingCartMaterVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.shopmanage.service.IShopService;
import com.pur.zsms.supplier.service.ISupplierService;
import com.pur.zsms.systemsetting.datadictionary.service.IDataDictionaryService;

@Controller
@RequestMapping(value = "/materSup")
public class MaterControllorForSupplier {

	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(MaterControllorForSupplier.class);

	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "materService")
	private IMaterService materService;

	@Resource(name = "shopService")
	private IShopService shopService;

	@Resource(name = "supplierService")
	private ISupplierService supplierService;

	@Resource(name = "dictionaryService")
	private IDataDictionaryService dataDictionaryService;

	@RequestMapping(value = "/findSelectMaterForBuySupplier.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findSelectMaterForBuySupplier(@RequestParam(required = false) String page, @RequestParam(required = false) String rows,
			MaterVo materVo, HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));

		UserPo userInfo = (UserPo) session.getAttribute("user");
		materVo.setSupId(supplierService.getSupIdByUserId(userInfo.getUserId()));
		this.pageList = materService.listSelectMater(pageController, materVo);
		List<MaterVo> materList = new ArrayList<MaterVo>();
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				MaterVo f = new MaterVo();
				f.setMaterId((Integer) item[0]);
				f.setMaterName((String) item[1]);
				f.setMaterType((Integer) item[2]);
				f.setMaterLevel((Integer) item[3]);
				f.setMaterValue(((BigDecimal) item[4]).multiply(new BigDecimal("1000")));
				f.setMaterProportion((Integer) item[6]);
				f.setMid((Integer) item[7]);
				f.setSupId((Integer) item[8]);
				f.setSupName((String) item[9]);
				f.setMaterValueUndressed(((BigDecimal) item[10]).multiply(new BigDecimal("1000")));
				f.setUnit((String) item[11]);
				f.setSpecifications((String) item[12]);
				f.setBrands((String) item[13]);
				f.setMaterValueContent("材料价格波动");
				materList.add(f);
			}
		}
		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", materList);
		log.info("----" + json.toString());
		return json.toString();
	}

	@RequestMapping(value = "/addShoppingCart.do", method = { RequestMethod.POST })
	@ResponseBody
	public String addShoppingCart(ShoppingCartMaterSupplierVo c, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			c.setSupId(supId);

			boolean flag = materService.addShoppingCartSup(c);
			if (flag) {
				json.put("success", true);
			} else {
				json.put("success", false);
				json.put("msg", materService.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		return json.toString();
	}

	@RequestMapping(value = "/findShoppingCartMater.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findShoppingCartMater(@RequestParam(required = false) String page, @RequestParam(required = false) String rows,
			ShoppingCartMaterVo shoppingCartMaterVo, HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		page = "1";
		rows = "1000";

		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));

		UserPo userInfo = (UserPo) session.getAttribute("user");
		shoppingCartMaterVo.setSupId(supplierService.getSupIdByUserId(userInfo.getUserId()));
		this.pageList = materService.findShoppingCartMaterSupplier(pageController, shoppingCartMaterVo);
		List<ShoppingCartMaterVo> shoppingCartMaterVoList = new ArrayList<ShoppingCartMaterVo>();
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				ShoppingCartMaterVo f = new ShoppingCartMaterVo();
				f.setSid((Integer) item[0]);
				f.setMaterId((Integer) item[1]);
				f.setMaterLevel((Integer) item[2]);
				// f.setMaterValueUndressed(((BigDecimal) item[3]).multiply(new
				// BigDecimal(1000)));
				f.setSupId((Integer) item[4]);
				f.setMaterNum((BigDecimal) item[5]);
				f.setMaterName((String) item[6]);
				f.setUnit((String) item[7]);
				f.setSpecifications((String) item[8]);
				f.setBrands((String) item[9]);
				if (item[10] != null) {
					f.setMaterValueCost(((BigDecimal) item[10]).multiply(new BigDecimal(1000)));
				}
				f.setLeaveMessage((String) item[11]);
				shoppingCartMaterVoList.add(f);
			}
		}
		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", shoppingCartMaterVoList);
		return json.toString();
	}

	@RequestMapping(value = "/deleteShoppingCartOne.do", method = { RequestMethod.POST })
	@ResponseBody
	public String deleteShoppingCartOne(ShoppingCartMaterVo c, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			boolean flag = materService.deleteShoppingCartSup(c);
			if (flag) {
				json.put("success", true);
			} else {
				json.put("success", false);
				json.put("msg", materService.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		return json.toString();
	}

	@RequestMapping(value = "/searchMaterValueCostLast.do", method = { RequestMethod.POST })
	@ResponseBody
	public String searchMaterValueCostLast(int materId, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			BigDecimal materValue = materService.getMaterValueCostLast(materId, supplierService.getSupIdByUserId(userInfo.getUserId()));
			json.put("materValue", materValue);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		return json.toString();
	}

	@RequestMapping(value = "/findMater.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findMater(@RequestParam(required = false) String page, @RequestParam(required = false) String rows, MaterVoForSup materVo,
			HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		materVo.setSupId(supplierService.getSupIdByUserId(userInfo.getUserId()));
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		this.pageList = materService.listMaterForSup(pageController, materVo);
		List<MaterVoForSup> materList = new ArrayList<MaterVoForSup>();
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				MaterVoForSup f = new MaterVoForSup();
				f.setMaterId((Integer) item[0]);
				f.setMaterName((String) item[1]);
				f.setMaterType((Integer) item[2]);
				f.setMaterLevel((Integer) item[3]);
				f.setMaterValue(((BigDecimal) item[4]).multiply(new BigDecimal("1000")));
				f.setMaterProportion((Integer) item[5]);
				f.setMaterDescribe((String) item[6]);
				f.setSupId((Integer) item[7]);
				f.setSupName((String) item[8]);

				f.setMaterValueUndressed(((BigDecimal) item[9]).multiply(new BigDecimal("1000")));

				f.setUnit((String) item[10]);
				f.setSpecifications((String) item[11]);
				f.setBrands((String) item[12]);
				f.setDeleteFlag((Integer) item[13]);
				if (item[14] != null) {
					f.setLowLimit((String) item[14]);
				}
				if (item[15] != null) {
					f.setUpperLimit((String) item[15]);
				}

				if (item[16] != null) {
					f.setCheckCostId(Integer.valueOf(item[16].toString()));
				}

				if (item[17] != null) {
					f.setLowLimitSale((String) item[17]);
				}
				if (item[18] != null) {
					f.setUpperLimitSale((String) item[18]);
				}

				if (item[19] != null) {
					f.setCheckSaleId(Integer.valueOf(item[19].toString()));
				}

				if (item[20] != null) {
					f.setSupSupName(item[20].toString());
				} else {
					f.setSupSupName("无绑定");
				}

				if (item[21] != null) {
					f.setSupSupId(Integer.valueOf(item[21].toString()));
				} else {
					f.setSupSupId(0);
				}

				materList.add(f);
			}
		}
		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", materList);
		log.info("----" + json.toString());
		return json.toString();
	}

	@RequestMapping(value = "/addCheckMaterValue.do", method = { RequestMethod.POST })
	@ResponseBody
	public String addCheckMaterValue(MaterVoForSup c, HttpSession session) {
		JSONObject json = new JSONObject();

		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			c.setSupId(supplierService.getSupIdByUserId(userInfo.getUserId()));
			boolean flag = materService.addCheckMaterCost(c);
			if (flag) {
				json.put("success", true);
			} else {
				json.put("success", false);
				json.put("msg", materService.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		return json.toString();
	}

	@RequestMapping(value = "/getLastShipmentValue.do", method = { RequestMethod.POST })
	@ResponseBody
	public String getLastShipmentValue(HttpSession session, HttpServletRequest request, HttpServletResponse response, int materId, long shopId) {
		JSONObject json = new JSONObject();
		json.put("success", true);
		BigDecimal materValue = new BigDecimal(0);

		UserPo userInfo = (UserPo) session.getAttribute("user");
		BigDecimal materValueReal = new BigDecimal(0);
		try {
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			materValue = supplierService.getMaterValueRealLastByMaterId(materId, supId, shopId);

		} catch (GenericException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		json.put("materValue", materValue);
		return json.toString();
	}

	@RequestMapping(value = "/getLastShipmentValueForDistributor.do", method = { RequestMethod.POST })
	@ResponseBody
	public String getLastShipmentValueForDistributor(HttpSession session, HttpServletRequest request, HttpServletResponse response, int materId,
			long distributId) {
		JSONObject json = new JSONObject();
		json.put("success", true);
		BigDecimal materValue = new BigDecimal(0);

		UserPo userInfo = (UserPo) session.getAttribute("user");
		BigDecimal materValueReal = new BigDecimal(0);
		try {
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			/*materValue = supplierService.getLastShipmentValueForDistributor(materId, supId, distributId);

			materValue = supplierService.getMaterValueRealLastByMaterId(materId, supId, shopId);*/

		} catch (GenericException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		json.put("materValue", materValue);
		return json.toString();
	}

	@RequestMapping(value = "/bindingMaterSupOne.do", method = { RequestMethod.POST })
	@ResponseBody
	public String bindingMaterSupOne(MaterVoForSup c, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			boolean flag = materService.bindingMaterSupOne(c);
			if (flag) {
				json.put("success", true);
			} else {
				json.put("success", false);
				json.put("msg", materService.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		return json.toString();
	}

	@RequestMapping(value = "/bindingMaterSupBatch.do", method = { RequestMethod.POST })
	@ResponseBody
	public String bindingMaterSupBatch(MaterVoForSup c, HttpSession session) {
		JSONObject json = new JSONObject();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		try {
			c.setDistributorId(supplierService.getSupIdByUserId(userInfo.getUserId()));
			boolean flag = materService.bindingMaterSupBatch(c);
			if (flag) {
				json.put("success", true);
			} else {
				json.put("success", false);
				json.put("msg", materService.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		return json.toString();
	}

}
